package org.swust.sysmonitorapp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.swust.sysmonitorapp.config.SecurityUserDetails;
import org.swust.sysmonitorapp.dto.HealthDataDto;
import org.swust.sysmonitorapp.entity.HealthData;
import org.swust.sysmonitorapp.entity.QHealthData;
import org.swust.sysmonitorapp.entity.R;
import org.swust.sysmonitorapp.entity.SysUser;
import org.swust.sysmonitorapp.service.AmqpMessageService;
import org.swust.sysmonitorapp.service.IHealthDataService;
import org.swust.sysmonitorapp.service.ISysUserService;

import java.util.Map;

/**
 * 健康数据控制器
 *
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/health")
public class HealthDataController {

    // 开发阶段测试用的固定用户ID
    private static final Long TEST_USER_ID = 2L;
    
    // 开发测试模式标志，生产环境中设置为false
    private static final boolean DEV_TEST_MODE = true;

    @Autowired
    private IHealthDataService healthDataService;
    
    @Autowired
    private ISysUserService userService;

    private final AmqpMessageService messageService;

    public HealthDataController(AmqpMessageService messageService) {
        this.messageService = messageService;
    }

    @GetMapping("/messages")
    public Object getMessages() {
        return messageService.getMessages();
    }

    /**
     * 获取当前用户健康数据列表
     *
     * @param page 分页参数
     * @param query 查询参数
     * @return 健康数据列表
     */
    @GetMapping("/mydata")
    public R<IPage<HealthDataDto>> getMyHealthData(Page page, QHealthData query) {
        Long userId = getCurrentUserId();
        query.setUserId(userId);
        return R.ok(healthDataService.pageHealthData(page, query));
    }

    // 获取用户最新心率血氧数据
    @GetMapping("/latest/{deviceId}")
    public R<HealthDataDto> getLatestData(@PathVariable String deviceId) {
        return R.ok(healthDataService.getLatestData(deviceId));
    }

    /**
     * 获取当前用户心率统计数据
     *
     * @param startTime 开始时间 (yyyy-MM-dd HH:mm:ss)
     * @param endTime 结束时间 (yyyy-MM-dd HH:mm:ss)
     * @return 心率统计数据
     */
    @GetMapping("/heart-rate/stats")
    public R<Map<String, Object>> getHeartRateStats(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        Long userId = getCurrentUserId();
        return R.ok(healthDataService.getUserHeartRateStats(userId, startTime, endTime));
    }

    /**
     * 获取当前用户血氧统计数据
     *
     * @param startTime 开始时间 (yyyy-MM-dd HH:mm:ss)
     * @param endTime 结束时间 (yyyy-MM-dd HH:mm:ss)
     * @return 血氧统计数据
     */
    @GetMapping("/blood-oxygen/stats")
    public R<Map<String, Object>> getBloodOxygenStats(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        Long userId = getCurrentUserId();
        return R.ok(healthDataService.getUserBloodOxygenStats(userId, startTime, endTime));
    }

    /**
     * 添加健康数据
     *
     * @param healthData 健康数据
     * @return 操作结果
     */
    @PostMapping
    public R<Boolean> addHealthData(@RequestBody HealthData healthData) {
        healthData.setUserId(getCurrentUserId());
        return R.ok(healthDataService.save(healthData));
    }

    /**
     * 获取当前登录用户ID
     * 在开发测试模式下，返回固定的测试用户ID
     *
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        // 开发测试模式，直接返回测试用户ID
        if (DEV_TEST_MODE) {
            return TEST_USER_ID;
        }
        
        // 正常模式，获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || 
            authentication instanceof AnonymousAuthenticationToken) {
            throw new RuntimeException("用户未登录，请先登录");
        }
        
        Object principal = authentication.getPrincipal();
        
        // 处理不同类型的Principal
        if (principal instanceof SecurityUserDetails) {
            return ((SecurityUserDetails) principal).getUser().getUserId();
        } else if (principal instanceof String) {
            // 如果是匿名用户，直接抛出异常
            if ("anonymousUser".equals(principal)) {
                throw new RuntimeException("用户未登录，请先登录");
            }
            
            // 从用户名查询用户
            String username = (String) principal;
            SysUser user = userService.getUserByUsername(username);
            if (user == null) {
                throw new RuntimeException("无法找到用户: " + username);
            }
            return user.getUserId();
        } else {
            throw new RuntimeException("无法识别的用户主体类型: " + principal.getClass().getName());
        }
    }
} 